package com.allwees.support.payment.encryptor;


import com.allwees.core.common.util.encrypt.BASE64;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author mhn
 */
@Slf4j
public class CreditCardEncryptor {
    private static final byte[] DEFAULT_SEED = "41d0.#b110042@ab".getBytes();
    public static final String CARD_SEED = "136.#1fh@ab";

	public static String decrypt(String content) {
		return decrypt(content,DEFAULT_SEED);
	}

	public static String encrypt(String content) {
		return encrypt(content, DEFAULT_SEED);
	}

	public static String encrypt(String content,String seed) {
		return encrypt(content, seed.getBytes());
	}

    public static String decrypt(String content, String seed) {
        return decrypt(content, seed.getBytes());
    }

	public static String decrypt(String content, byte[] seed) {
		try {
			byte[] encrypted = BASE64.decryptBASE64(content);
			Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding");
			SecretKeySpec keyspec = new SecretKeySpec(seed, "AES");
			IvParameterSpec ivspec = new IvParameterSpec(seed);
			cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
			return new String(cipher.doFinal(encrypted)).trim();
		} catch (Exception e) {
			log.error(">>>>>>>>>>>> aes 解密,content:{}", content, e);
			throw new RuntimeException(e);
		}
	}

    public static String encrypt(String data, byte[] seed) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding");   //参数分别代表 算法名称/加密模式/数据填充方式
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(seed, "AES");
            IvParameterSpec ivspec = new IvParameterSpec(seed);
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return BASE64.encodeBase64(new String(encrypted));
        } catch (Exception e) {
            log.error(">>>>>>>>>>>> aes 加密,data:{}", data, e);
            throw new RuntimeException(e);
        }
    }
}
